const axios = require('axios');

class AlphaVantageService {
  constructor() {
    this.apiKey = process.env.ALPHA_VANTAGE_API_KEY || 'demo';
    this.baseUrl = 'https://www.alphavantage.co/query';
  }

  // 转换股票代码格式以适配Alpha Vantage
  convertSymbolForAlphaVantage(symbol) {
    // 检查symbol是否定义
    if (!symbol) {
      throw new Error('symbol is not defined');
    }
    
    console.log(`Converting symbol: ${symbol}`);
    
    // 中国A股市场代码转换
    if (symbol.startsWith('000') || symbol.startsWith('002') || symbol.startsWith('300')) {
      // 深圳证券交易所股票
      const converted = symbol + '.SZ';
      console.log(`Converted ${symbol} to ${converted} (Shenzhen)`);
      return converted;
    } else if (symbol.startsWith('600') || symbol.startsWith('601') || symbol.startsWith('603') || symbol.startsWith('688')) {
      // 上海证券交易所股票
      const converted = symbol + '.SH';
      console.log(`Converted ${symbol} to ${converted} (Shanghai)`);
      return converted;
    }
    
    // 美股或其他市场代码保持不变
    console.log(`Keeping ${symbol} unchanged`);
    return symbol;
  }

  // 获取股票实时数据
  async getRealTimeData(symbol) {
    try {
      const convertedSymbol = this.convertSymbolForAlphaVantage(symbol);
      console.log(`Fetching real-time data for ${symbol} (converted to ${convertedSymbol})`);
      
      const response = await axios.get(this.baseUrl, {
        params: {
          function: 'GLOBAL_QUOTE',
          symbol: convertedSymbol,
          apikey: this.apiKey
        },
        timeout: 10000 // 10秒超时
      });

      const data = response.data['Global Quote'];
      if (!data) {
        throw new Error(`No data returned from Alpha Vantage for symbol ${convertedSymbol}. This may be due to an invalid symbol, API key issue, or network problem.`);
      }

      return {
        symbol: symbol, // 返回原始符号
        open: parseFloat(data['02. open']),
        high: parseFloat(data['03. high']),
        low: parseFloat(data['04. low']),
        price: parseFloat(data['05. price']),
        volume: parseInt(data['06. volume']),
        latestTradingDay: data['07. latest trading day'],
        previousClose: parseFloat(data['08. previous close']),
        change: parseFloat(data['09. change']),
        changePercent: data['10. change percent'].replace('%', '')
      };
    } catch (error) {
      throw new Error(`Error fetching real-time data for ${symbol}: ${error.message}`);
    }
  }

  // 获取股票历史数据（带重试机制）
  async getHistoricalData(symbol, interval = 'daily', retries = 3) {
    // 检查symbol是否定义
    if (!symbol) {
      throw new Error('symbol is not defined');
    }
    
    for (let attempt = 1; attempt <= retries; attempt++) {
      try {
        const convertedSymbol = this.convertSymbolForAlphaVantage(symbol);
        console.log(`Fetching historical data for ${symbol} (converted to ${convertedSymbol}), attempt ${attempt}`);
        
        let functionType;
        switch (interval) {
          case 'daily':
            functionType = 'TIME_SERIES_DAILY';
            break;
          case 'weekly':
            functionType = 'TIME_SERIES_WEEKLY';
            break;
          case 'monthly':
            functionType = 'TIME_SERIES_MONTHLY';
            break;
          default:
            functionType = 'TIME_SERIES_DAILY';
        }

        const response = await axios.get(this.baseUrl, {
          params: {
            function: functionType,
            symbol: convertedSymbol,
            apikey: this.apiKey
          },
          timeout: 15000 // 15秒超时
        });

        // 检查是否是API限制错误
        if (response.data['Error Message']) {
          throw new Error(`Alpha Vantage API Error: ${response.data['Error Message']}`);
        }

        // 检查是否是API调用频率限制
        if (response.data['Note']) {
          const note = response.data['Note'];
          console.warn(`API Note: ${note}`);
          // 如果是频率限制，等待一段时间再重试
          if (note.includes('higher call frequency')) {
            const waitTime = attempt * 15000; // 等待时间递增
            console.log(`Rate limited. Waiting ${waitTime}ms before retry attempt ${attempt}...`);
            await this.wait(waitTime);
            continue;
          }
        }

        const timeSeriesKey = `Time Series (${interval.charAt(0).toUpperCase() + interval.slice(1)})`;
        const timeSeriesData = response.data[timeSeriesKey];

        if (!timeSeriesData) {
          throw new Error(`No historical data returned from Alpha Vantage for symbol ${convertedSymbol}. This may be due to an invalid symbol, API key issue, or network problem.`);
        }

        // 转换数据格式
        const historicalData = [];
        for (const date in timeSeriesData) {
          const data = timeSeriesData[date];
          historicalData.push({
            date: date,
            open: parseFloat(data['1. open']),
            high: parseFloat(data['2. high']),
            low: parseFloat(data['3. low']),
            close: parseFloat(data['4. close']),
            volume: parseInt(data['5. volume'])
          });
        }

        // 按日期排序
        historicalData.sort((a, b) => new Date(a.date) - new Date(b.date));

        return historicalData;
      } catch (error) {
        console.error(`Attempt ${attempt} failed for ${symbol}: ${error.message}`);
        
        // 如果是最后一次尝试，抛出错误
        if (attempt === retries) {
          throw new Error(`Error fetching historical data for ${symbol} after ${retries} attempts: ${error.message}`);
        }
        
        // 等待一段时间再重试
        const waitTime = attempt * 5000; // 等待时间递增
        console.log(`Waiting ${waitTime}ms before retry attempt ${attempt + 1}...`);
        await this.wait(waitTime);
      }
    }
  }

  // 获取技术指标 (示例: SMA)
  async getSMA(symbol, interval = 'daily', timePeriod = 20, seriesType = 'close') {
    try {
      const convertedSymbol = this.convertSymbolForAlphaVantage(symbol);
      console.log(`Fetching SMA data for ${symbol} (converted to ${convertedSymbol})`);
      
      const response = await axios.get(this.baseUrl, {
        params: {
          function: 'SMA',
          symbol: convertedSymbol,
          interval: interval,
          time_period: timePeriod,
          series_type: seriesType,
          apikey: this.apiKey
        },
        timeout: 10000 // 10秒超时
      });

      const smaData = response.data['Technical Analysis: SMA'];

      if (!smaData) {
        throw new Error(`No SMA data returned from Alpha Vantage for symbol ${convertedSymbol}. This may be due to an invalid symbol, API key issue, or network problem.`);
      }

      // 转换数据格式
      const smaArray = [];
      for (const date in smaData) {
        smaArray.push({
          date: date,
          sma: parseFloat(smaData[date]['SMA'])
        });
      }

      // 按日期排序
      smaArray.sort((a, b) => new Date(a.date) - new Date(b.date));

      return smaArray;
    } catch (error) {
      throw new Error(`Error fetching SMA data for ${symbol}: ${error.message}`);
    }
  }

  // 等待函数
  wait(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
  }
}

module.exports = new AlphaVantageService();